import SessionUserUtil from '../../../data/session/sessionUser'
import SessionSellingServerUtil from '../../../data/session/sessionSellingServer';
import SessionUtil, { JxbHttpClient } from '../../../data/session/session';
import { RtLogUtil } from '../../../utils/log';
const Common = require('../../../utils/common.js');
Page({
  data: {
    flag: true,
  },
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '账号登录'
    })
    SessionUtil.getInstance().then(session=>{
      if(options._r){
        this.setData({
          referer: options._r
        })
      }
      if (options.couponId) {
        this.setData({
          couponId: options.couponId
        })
      } else if (options.tasting) {
        this.setData({
          tasting: options.tasting,
          from: 'tasting'
        })
      } else if (options.from && options.from === 'userCenter') {
        this.setData({
          from: 'userCenter'
        })
      } else if (!options.couponId) {
        var name = SessionSellingServerUtil.getInstanceSync().getTheAgentSync().showName,
          renderData = {
            name: name,
            from: (typeof options.from === 'undefined') ? 7 : options.from,
            coupon_array: options.coupon_array ? options.coupon_array : []
          };
        if (options.checkedlis) {
          renderData.checkedlis = options.checkedlis;
        }
        if (options.fromMy) {
          renderData.fromMy = options.fromMy;
        }
        this.setData(renderData)
      }
      this.login().then(code => {
        return this.getSessionKey(code);
      }).then(()=>{
        let userid = SessionUserUtil.getInstanceSync().userId;
        this.setData({
          userid: userid
        })
      }).catch(data => {
        wx.showToast({
          title: data,
          image: '/pages/images/fail.png',
          duration: 2000
        })
      })
    })
    
  },
  onshow() {
    getApp().getSaleMode()
    SessionUtil.getInstance(()=>{
      let userid = SessionUserUtil.getInstanceSync().userId
      this.setData({
        userid: userid
      })
    })
  },

  /**微信登录 */
  login() {
    var p = new Promise(function (resolve, reject) {
      wx.login({
        success: function (res) {
          if (res.code) {
            resolve(res.code);
          }
        },
        fail: function (res) {
          reject(res.data.message);
        }
      })
    })
    return p;
  },

  /**刷新sessionKey */
  getSessionKey(code) {
    return (new JxbHttpClient).post({
      url: '/AppMaster/Login/refreshWxSessionKey',
        data: {
          code: code
        }
    }).then(jxbResp=>{
      console.log('getSessionKey success',jxbResp)
    }).catch(err=>{
      RtLogUtil.error('getSessionKey error',err.message, err.name, err.httpResponse)
      console.log('getSessionKey error',err)
    })
  },

  /**
   * 获取微信的手机号，并通过手机号登录
   * 
   * 获取手机号后执行自动登录操作
   * 
   * @todo 函数命名有问题
   * @param {*} e 
   */
  getPhoneNumber(e) {
    var page = this;
    var nickname = page.data.nickname;
    var avatarUrl = page.data.avatarUrl;
    (new JxbHttpClient).post({
      url: '/AppMaster/Login/wxGetPhoneAndLogin',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          name: nickname,
          user_img: avatarUrl
        }
    }).then(jxbResp=>{
      // todo 老的刷新缓存逻辑，需要剔除
      Common.when_user_change_clear_the_storage();
      // 刷新SessionUser和SellingServer缓存
      return Promise.all([SessionUserUtil.renewCache(), SessionSellingServerUtil.renewCache()])
    }).then(()=>{
      // 执行跳转逻辑
      this.ongoto()
    }).catch(err=>{
      console.log(err);
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  toNormalLogin() {
    this.setData({
      flag: !this.data.flag
    })
  },
  goHome(){
    wx.reLaunch({
      url: '/pages/index/index'
    });
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },
  onLogin_SMC: function () {
    var page = this;
    var userName = page.data.phones;
    var passWord = page.data.password;
    var phonetest = /^0?1\d{10}$/;
    if (!userName) {
      Common.Alert('提示', '请输入手机号码');
      return false;
    } else if (!phonetest.test(userName)) {
      Common.Alert('提示', '请输入正确的手机号码');
      return false;
    }
    if (!passWord) {
      Common.Alert('登录提示', '请输入登录密码');
      return false;
    }
    wx.showLoading({
      title: '正在登录...',
    });
    (new JxbHttpClient).post({
      url: 'AppMaster/Login/login',
      data: {
        userName: userName,
        password: passWord
      }
    }).then(jxbResp=>{
      wx.hideLoading();
      Common.when_user_change_clear_the_storage();
      wx.setStorageSync('user_id', jxbResp.data.userId);
      wx.setStorageSync('phone', userName);
      // 刷新SessionUser和SellingServer缓存
      return Promise.all([SessionUserUtil.renewCache(), SessionSellingServerUtil.renewCache()])
    }).then(()=>{
      page.ongoto();
    }).catch(err=>{
      wx.hideLoading();
      Common.Alert('登录提示', err.message);
    })
  },
  updatepassword: function (e) {
    this.setData({
      password: e.detail.value
    })
  },
  updatephones: function (e) {
    this.setData({
      phones: e.detail.value
    })
  },

  forgetPassword: function () {
    wx.navigateTo({
      url: '/pages/login/forget_password/forget_password'
    })
  },

  ongoto: function () {
    var page = this;
    if (page.data.from == 0) {
      (new JxbHttpClient).post({
        url: '/AppMaster/PosCart/PosAddCart',
        data: {
          number: 1,
          itemId: this.data.checkedlis
        }
      }).then(jxbResp=>{
        wx.redirectTo({
          url: '/pages/product/orderConfirm/index?checkedlis=' + this.data.checkedlis
        });
      }).catch(err=>{
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    } else if (page.data.from == 1) {
      wx.redirectTo({
        url: '/pages/coupon/use/use?coupon_array=' + page.data.coupon_array + '&is_useCoupon=showAllCoupon'
      })
    } else if (page.data.from == 2) {
      wx.redirectTo({
        url: '/pages/coupon/index/index'
      })
    } else if (page.data.from == 3) {
      wx.redirectTo({
        url: '/pages/my/address/address'
      })
    } else if (page.data.from == 4 && !page.data.referer) {
      wx.setStorageSync("if_refresh", 5);
      wx.navigateBack(1);
    } else if (page.data.from == 5) {
      wx.redirectTo({
        url: '/pages/order/index/index?fromMy=' + page.data.fromMy,
      })
    } else if (page.data.from == 6) {
      wx.redirectTo({
        url: '/pages/product/orderConfirm/index?checkedlis=' + page.data.checkedlis
      });
    } else if (page.data.from == 7 || typeof page.data.from === 'undefined') {
      wx.reLaunch({
        url: '/pages/index/index'
      });
    } else if (page.data.from == 8){
        wx.navigateBack()
    } else if (page.data.couponId) {
      wx.redirectTo({
        url: '/pages/my/redpacket/redpacket?id=' + page.data.couponId
      });
    } else if (page.data.from === 'tasting') {
      wx.navigateTo({
        url: '/pages/tasting/index?coupon=' + page.data.tasting,
      })
    } else if (page.data.from === 'userCenter') {
      wx.switchTab({
        url: '/pages/my/index/index',
      })
    } else {
      if(page.data.referer){
        let referer = decodeURIComponent(page.data.referer)
        if(referer.indexOf('/') !== 0) referer = '/' + referer;
        wx.redirectTo({
            url: referer,
            fail: () => {
              // 出错后尝试切换tab
              wx.switchTab({
                url: referer,
                fail: err=>{
                    console.log('跳转到来源页面失败',referer, err)
                    wx.switchTab({
                        url: '/pages/index/index',
                    })
                },
              })
            }
        });
      }else{
        console.log('没有来源', page.data)
          wx.switchTab({
              url: '/pages/index/index',
          })
      }
    }
  }
})